package com.jyx.healthsys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyx.Data_unification.Unification;
import com.jyx.healthsys.entity.HealthKnowledge;
import com.jyx.healthsys.entity.Notice;
import com.jyx.healthsys.service.IHealthKnowledgeService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
class HealthPo{
    private HealthKnowledge healthKnowledge;
    private Long pageNo;
    private Long pageSize;
}
@RestController
@RequestMapping("/health-knowledge")
public class HealthKnowledgeController {
    @Autowired
    private IHealthKnowledgeService healthKnowledgeService;
    @PostMapping("/list")
    Unification<Map<String,Object>> getNotices(@RequestBody HealthPo healthPo){
        // 构造查询条件
        LambdaQueryWrapper<HealthKnowledge> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(healthPo.getHealthKnowledge().getTitle()), HealthKnowledge::getTitle, healthPo.getHealthKnowledge().getTitle());
        wrapper.like(!StringUtils.isEmpty(healthPo.getHealthKnowledge().getCategory()), HealthKnowledge::getCategory, healthPo.getHealthKnowledge().getCategory());
        wrapper.eq(!StringUtils.isEmpty(healthPo.getHealthKnowledge().getPublishedDate()), HealthKnowledge::getPublishedDate, healthPo.getHealthKnowledge().getPublishedDate());
        wrapper.orderByDesc(HealthKnowledge::getPublishedDate);

        // 分页查询
        Page<HealthKnowledge> page = new Page<>(healthPo.getPageNo(), healthPo.getPageSize());
        healthKnowledgeService.page(page, wrapper);

        // 将查询结果封装到Map中返回
        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());
        return Unification.success(data);
    }
    @PostMapping("/add")
    Unification<Integer> addNotice(@RequestBody HealthKnowledge healthKnowledge){
        healthKnowledge.setPublishedDate(String.valueOf(LocalDate.now()));
        boolean save = healthKnowledgeService.saveOrUpdate(healthKnowledge);
        if (save){
            return Unification.success();
        }
        return Unification.fail("添加失败");
    }
    @GetMapping("/delete")
    Unification<Integer> deleteNotice(@RequestParam Integer id){
        boolean remove = healthKnowledgeService.removeById(id);
        if (remove){
            return Unification.success();
        }
        return Unification.fail("删除失败");
    }
}
